package com.dtr.zxing.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationConfiguration.LocationMode;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.dtr.zxing.R;

public class ResultActivity extends Activity  implements OnGetGeoCoderResultListener {

	// 定位相关
	LocationClient mLocClient;
	public MyLocationListenner myListener = new MyLocationListenner();
	private LocationMode mCurrentMode;
	BitmapDescriptor mCurrentMarker;
	boolean isFirstLoc = true;// 是否首次定位
	
	private String tag = "resultActivity";
	MapView mMapView = null;
	BaiduMap mBaiduMap = null;
	MyLocationData locData;
	
	GeoCoder mSearch = null; // 搜索模块，也可去掉地图模块独立使用
	
	private SDKReceiver mReceiver;
	String erCodeResult = null;
	
	Handler mHandler = null;
	public static final int SEARCH_ERCODE_RESULT = 0;
	public static final int MEASURE_DISTANCE = 1;
	public static final int DRAW_LINE = 2;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		mHandler = new Handler()
		{
			public void handleMessage(android.os.Message msg) 
			{
				switch (msg.what)
				{
					case SEARCH_ERCODE_RESULT:

						//扫描二维码得到的信息
						mSearch.geocode(
								new GeoCodeOption()
								.city("北京")
								.address(erCodeResult)
								);
						
						break;
					case MEASURE_DISTANCE:
						
						GeoCodeResult Searchresult= (GeoCodeResult)msg.obj;
						//获取当前位置的经纬度
						LatLng startLatLng = new LatLng(locData.latitude,locData.longitude);//new LatLng(39.862732, 116.455832);//定位获取的位置（测试：北京万通中心D座）
						
						LatLng endLatLng = new LatLng(Searchresult.getLocation().latitude,
								Searchresult.getLocation().longitude);

						//计算距离
						double distance = getDistance(startLatLng,endLatLng);
						//绘图
						Log.e(tag, "distance is "+distance);
						Toast.makeText(ResultActivity.this, "您的包裹距离您所在位置大概还有："+distance+"米",
								Toast.LENGTH_LONG).show();
						
						break;
					case DRAW_LINE:
						break;
				}
			}
		};
		
		Bundle extras = getIntent().getExtras();
		erCodeResult = extras.getString("result");
		
		//在使用SDK各组件之前初始化context信息，传入ApplicationContext  
        //注意该方法要再setContentView方法之前实现  
        SDKInitializer.initialize(getApplicationContext());  
        setContentView(R.layout.activity_result);  
        //获取地图控件引用  
        mMapView = (MapView) findViewById(R.id.bmapView);  
        mBaiduMap = mMapView.getMap();  
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        
        //设置缩放级别
        float mZoomLevel = 15.0f;
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(mZoomLevel));
        
        
    		// 开启定位图层
 		mBaiduMap.setMyLocationEnabled(true);
 		
 		mCurrentMode = LocationMode.NORMAL;
		mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
						mCurrentMode, true, mCurrentMarker));
 		// 定位初始化
 		mLocClient = new LocationClient(this);
 		mLocClient.registerLocationListener(myListener);
 		LocationClientOption option = new LocationClientOption();
 		option.setOpenGps(true);// 打开gps
 		option.setCoorType("bd09ll"); // 设置坐标类型
 		option.setScanSpan(1000);
 		mLocClient.setLocOption(option);
 		mLocClient.start();
 		
 		
 		// 注册 SDK 广播监听者
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
		mReceiver = new SDKReceiver();
		registerReceiver(mReceiver, iFilter);
		

		// 初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(this);
	}
	

 	@Override  
    protected void onDestroy() {  
        super.onDestroy();  
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理  
        mMapView.onDestroy();  
    }  
 
 	@Override  
    protected void onResume() {  
        super.onResume();  
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理  
        mMapView.onResume();  
        }  

 	@Override  
    protected void onPause() {  
        super.onPause();  
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理  
        mMapView.onPause();  
        }  
	    

 	/**
	 * 构造广播监听类，监听 SDK key 验证以及网络异常广播
	 */
	public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
			Log.d("", "action: " + s);
			TextView text = (TextView) findViewById(R.id.result_text);
			text.setTextColor(Color.RED);
			if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
				text.setText("key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
			} else if (s
					.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
				text.setText("网络出错");
			}
		}
	}
    
    /**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
		 locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			
			Log.e("tag","latutude is "+locData.latitude+"long is "+locData.longitude);
			
			String text = "现在的位置为"+"\n经纬度分别为"+locData.latitude+", "+locData.longitude;
			
			LatLng ptCenter = new LatLng(locData.latitude,locData.longitude);
			// 反Geo搜索
			mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ptCenter));
			
			mBaiduMap.setMyLocationData(locData);
			
			if (isFirstLoc) {
				isFirstLoc = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				mBaiduMap.animateMapStatus(u);

				//定位得到消息后，发送搜索二维码的消息到消息队列
				Message msg = new Message();
				msg.what = SEARCH_ERCODE_RESULT;
				mHandler.sendMessage(msg);
			}
			
			
			
			//measureAndDrawLine();
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}
	}
	
	
	public  void measureAndDrawLine()
	{
		
	}
	
	/**
	 * 计算两点之间距离
	 * @param start
	 * @param end
	 * @return 米
	 */
	public double getDistance(LatLng start,LatLng end){
		double lat1 = (Math.PI/180)*start.latitude;
		double lat2 = (Math.PI/180)*end.latitude;
		
		double lon1 = (Math.PI/180)*start.longitude;
		double lon2 = (Math.PI/180)*end.longitude;
		
		
		//地球半径
		double R = 6371;
		
		//两点间距离 km，如果想要米的话，结果*1000就可以了
		double d =  Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))*R;
		
		return d*1000;
	}


	
	@Override
	public void onGetGeoCodeResult(GeoCodeResult result) {
		// TODO Auto-generated method stub
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(ResultActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
					.show();
			return;
		}
		
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*mBaiduMap.clear();
		mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.ic_launcher)));
		mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(result
				.getLocation()));*/
		
		Message msg = new Message();
		msg.what = MEASURE_DISTANCE;
		msg.obj = result;
		mHandler.sendMessage(msg);
		
		 
	}


	
	@Override
	public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
		// TODO Auto-generated method stub
		if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
			Toast.makeText(ResultActivity.this, "抱歉，未能找到结果", Toast.LENGTH_LONG)
					.show();
			return;
		}
		Toast.makeText(ResultActivity.this, "现在的位置在"+result.getAddress()+"附近",
				Toast.LENGTH_SHORT).show();
		
		Toast.makeText(ResultActivity.this, "正在计算扫描信息距离现在位置距离。。。",
				Toast.LENGTH_LONG).show();
	}
	    
	
}
